package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.animalNumber.entity.AnimalNumber;
import com.antdesignbackend.backend.animalNumber.service.AnimalNumberService;
import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.returnResult.ReturnCode;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.Enterprise;
import com.antdesignbackend.backend.entity.HarmlessReport;
import com.antdesignbackend.backend.entity.Production;
import com.antdesignbackend.backend.entity.Users;
import com.antdesignbackend.backend.entity.entityVo.HarmlessReportVo;
import com.antdesignbackend.backend.service.EnterpriseService;
import com.antdesignbackend.backend.service.HarmlessReportService;
import com.antdesignbackend.backend.service.ProductionService;
import com.antdesignbackend.backend.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/harmlessReportTreatment")
public class HarmlessReportTreatmentController extends BaseController {
    @Autowired
    HarmlessReportService harmlessReportService;

    @Autowired
    UserService userService;
    @Autowired
    ProductionService productionService;
    @Autowired
    AnimalNumberService animalNumberService;
    @Autowired
    EnterpriseService enterpriseService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private Integer menuId;

    @GetMapping("/index")
    @AuthToken
    public String ProductionIndex(String menuId) {
        this.menuId = Integer.parseInt(menuId);
        return "harmless/harmlessReportTreatment";
    }
    /**
     * 分页查询
     * @param harmlessReportVo
     * @return
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody HarmlessReportVo harmlessReportVo, HttpServletRequest request) {
        System.out.println("进入无害化处理信息表格查询");
        ReturnVO result = new ReturnVO();
        List<HarmlessReportVo> datalist=new ArrayList<>();
        try {
            QueryWrapper<HarmlessReportVo> queryWrapper = new QueryWrapper<>();
            QueryWrapper<Enterprise> enterpriseQueryWrapper=new QueryWrapper<>();
            //判断用户权限
            Users users = userService.getById(getLoginUserId());
            if (users.getAuthType() == 1){ //地市权限
                queryWrapper.eq("cityCode",users.getAuthCity());
            }else if (users.getAuthType() == 2){ //区县权限
                queryWrapper.eq("districtCode",users.getAuthDistrict());
            }else if (users.getAuthType() == 3){
                queryWrapper.eq("townCode",users.getAuthTown());
            }else {
                return result;
            }
            //根据地市查询
            if(harmlessReportVo.getCityCode() != null && !harmlessReportVo.getCityCode().equals("-1")){
                queryWrapper.eq("cityCode",harmlessReportVo.getCityCode());
            }
            if(harmlessReportVo.getDistrictCode() != null && !harmlessReportVo.getDistrictCode().equals("-1")){
                queryWrapper.eq("districtCode",harmlessReportVo.getDistrictCode());
            }
            if(harmlessReportVo.getTownCode() != null && !harmlessReportVo.getTownCode().equals("-1")){
                queryWrapper.eq("townCode",harmlessReportVo.getTownCode());
            }
            if (harmlessReportVo.getEnterpriseName() != null && !harmlessReportVo.getEnterpriseName().equals(""))
                queryWrapper.like("enterpriseName",harmlessReportVo.getEnterpriseName());
            if (harmlessReportVo.getTimeInterval() != null && !harmlessReportVo.getTimeInterval().equals("")){
                String[] str=harmlessReportVo.getTimeInterval().split(" - ");
                String star=str[0];
                String end=str[1];
                queryWrapper.between("createTime",star,end);
            }
            if (harmlessReportVo.getStatus() != null && !harmlessReportVo.getStatus().equals("")){
                queryWrapper.eq("status",harmlessReportVo.getStatus());
            }
            queryWrapper.orderByDesc("createTime");
            //先统计满足条件的数据总数，因为sql 不包括排序
            int total=harmlessReportService.count(queryWrapper);
            result.setTotal(total);
            //再查询
            if(total>0)
            {
                datalist= harmlessReportService.search(queryWrapper,new Page<>(harmlessReportVo.getPageIndex(),harmlessReportVo.getPageSize()));
                if (datalist.size() > 0){
                    for (HarmlessReportVo harmlessReportVo1:datalist){
                        if (harmlessReportVo1.getImg() != null && !harmlessReportVo1.getImg().equals("")){
                            harmlessReportVo1.setImg(WebConfig.host+"images/"+harmlessReportVo1.getImg());
                        }
                        if (harmlessReportVo1.getDeclareImage() != null && !harmlessReportVo1.getDeclareImage().equals("")){
                            harmlessReportVo1.setDeclareImageUrl(WebConfig.host+"images/"+harmlessReportVo1.getDeclareImage());
                        }
                        if (harmlessReportVo1.getHarmlessId() != null && !harmlessReportVo1.getHarmlessId().equals("")){
                            enterpriseQueryWrapper.eq("EnterpriseId",harmlessReportVo1.getHarmlessId());
                            Enterprise enterprise=enterpriseService.getOne(enterpriseQueryWrapper);
                            harmlessReportVo1.setHarmlessName(enterprise.getEnterpriseName());
                        }
                    }
                }
            }
            System.out.println("无害化处理信息"+datalist);
            result.setData(datalist);
        }catch (Exception e){
            System.out.println("出错啦！！！");
            logger.error(e.getMessage());
        }
        return result;
    }

    /**
     * 运输
     * @param harmlessReport
     * @return
     */
    @PostMapping("/transport")
    @ResponseBody
    @AuthToken
    public ReturnVO transport(@RequestBody HarmlessReport harmlessReport) {
        try {
            //设置运输时间
            harmlessReport.setTransportationTime(new Date());
            //设置状态
            harmlessReport.setStatus(2);
            harmlessReportService.updateById(harmlessReport);
            return new ReturnVO();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    /**
     * 处理
     * @param harmlessReport
     * @return
     */
    @PostMapping("/treatment")
    @ResponseBody
    @AuthToken
    public ReturnVO treatment(@RequestBody HarmlessReport harmlessReport) {
        try {
            //设置处理时间
            harmlessReport.setProcessingTime(new Date());
            //监管人
            harmlessReport.setSupervise(getLoginUserId()+"");
            //设置状态
            harmlessReport.setStatus(3);
            harmlessReport.setStatus(3);
            harmlessReportService.updateById(harmlessReport);
            harmlessReport = harmlessReportService.getById(harmlessReport.getHarmlessReportID());
            //添加死淘记录
            Production production = new Production();
            production.setUid(harmlessReport.getUserId());
            production.setEid(harmlessReport.getEid());
            production.setChangeTime(new Date());
            production.setSituation("死淘");
            production.setAnimalType(getLoginAnimal());

            //判断动物类型
            if (harmlessReport.getAnimalTypes() == 1){
                production.setMale(harmlessReport.getSpecies());
                production.setFemale(harmlessReport.getReserve());
                production.setBreedFemale(harmlessReport.getMenstruation());
                production.setLactation(harmlessReport.getLactation());
                production.setConservation(harmlessReport.getConservation());
                production.setGrow(harmlessReport.getCommodity());
            }else {
                production.setNumber(harmlessReport.getLivestock());
            }
            productionService.save(production);
            //修改动物数量
            //获得原有的值
            if (harmlessReport.getAnimalTypes() == 1){
                AnimalNumber animalNumber = animalNumberService.getById(harmlessReport.getBatch());
                if (animalNumber != null){
                    animalNumber.setSpecies(animalNumber.getSpecies() - harmlessReport.getSpecies());
                    animalNumber.setReserve(animalNumber.getReserve() - harmlessReport.getReserve());
                    animalNumber.setMenstruation(animalNumber.getMenstruation() - harmlessReport.getMenstruation());
                    animalNumber.setLactation(animalNumber.getLactation() - harmlessReport.getLactation());
                    animalNumber.setConservation(animalNumber.getConservation() - harmlessReport.getConservation());
                    animalNumber.setCommodity(animalNumber.getCommodity() - harmlessReport.getCommodity());
                    animalNumberService.updateById(animalNumber);
                }
            }else {
                QueryWrapper<AnimalNumber> wrapper = new QueryWrapper<>();
                wrapper.eq("channel",1);
                wrapper.eq("eid",harmlessReport.getEid());
                List<AnimalNumber> list = animalNumberService.list(wrapper);
                if (!list.isEmpty()){
                    AnimalNumber animalNumber = list.get(0);
                    animalNumber.setLivestock(animalNumber.getLivestock() - harmlessReport.getLivestock());
                    animalNumberService.updateById(animalNumber);
                }
            }
            return new ReturnVO();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }
}
